package com.example.service.impl;

import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import com.example.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author xqz
 * @description TODO
 * @dateTime 2023/5/30 9:26
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public User checkUser(String username, String password) {
        User userInfo = userMapper.getUserInfoByUserName(username);
        System.out.println(userInfo);
        if (userInfo == null || !userInfo.getUserPassword().equals(password)) {
            return null;
        }
        return userInfo;
    }

    @Override
    public List<UserVO> queryAllUserVO(String userName) {
        List<UserVO> userVOS = new ArrayList<>();            //创建：返回值
        List<User> users = userMapper.getAllUsers(userName);  //查询到：单表查询到user集合

        for(User user:users) {                           //遍历：users
            UserVO userVo = new UserVO();
            BeanUtils.copyProperties(user, userVo); //将user值注入：userVo
            userVOS.add(userVo);
        }

        return userVOS;
    }

    @Override
    public Long queryUserNums() {
        return userMapper.selUserCount();
    }

    @Override
    public int updateUserInfo(User user) {

        int state = 0;
        User oldUser = userMapper.selUserByUserId(user.getUserId());

        if(null == user.getUserName() || "".equals(user.getUserName()))
            user.setUserName(oldUser.getUserName());
        if(null == user.getUserEmail() || "".equals(user.getUserEmail()))
            user.setUserEmail(oldUser.getUserEmail());
        if(null == user.getUserAge() || "".equals(user.getUserAge()))
            user.setUserAge(oldUser.getUserAge());

        user.setUserPassword(user.getUserPassword());

        state = userMapper.updUserByUser(user);   //更新用户信息
        return state;
    }

    //5、添加用户：通过user对象进行添加
    @Override
    public int insUserByUser(User user) {
        user.setType(0);
        user.setCreateTime(new Date());
        user.setUserPassword(user.getUserPassword());

        return userMapper.insertUserByUser(user);
    }

    //6、删除用户：通过userId
    @Override
    public int delUserByUserId(Long userId) {
        return userMapper.deleteUserByUserId(userId);
    }

    //根据用户id查询用户信息
    @Override
    public User queryUserById(Long id) {
        User user = userMapper.selUserByUserId(id);
        return user;
    }

}
